package com.CommunityHub.kiana.controller;

import com.CommunityHub.kiana.po.ResidenceInfo;
import com.CommunityHub.kiana.po.User;
import com.CommunityHub.kiana.service.MemberService;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;

@WebServlet("/EditOccupantServlet")
public class EditOccupantServlet extends HttpServlet {
    private final MemberService memberService = new MemberService();
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("user");

        if (loginUser == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        try {
            int residenceId = Integer.parseInt(request.getParameter("id"));
            ResidenceInfo occupant = memberService.getOccupantById(residenceId);

            if (occupant == null) {
                session.setAttribute("error", "找不到指定的入住人信息");
                response.sendRedirect("ViewOccupantsServlet");
                return;
            }

            request.setAttribute("occupant", occupant);
            request.getRequestDispatcher("/editOccupant.jsp").forward(request, response);

        } catch (NumberFormatException e) {
            session.setAttribute("error", "无效的入住人ID格式");
            response.sendRedirect("ViewOccupantsServlet");
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("error", "系统错误: " + e.getMessage());
            response.sendRedirect("ViewOccupantsServlet");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("user");

        if (loginUser == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        try {
            int residenceId = Integer.parseInt(request.getParameter("residenceId"));
            String occupantName = request.getParameter("occupantName");
            String relationship = request.getParameter("relationship");
            int age = Integer.parseInt(request.getParameter("age"));
            String gender = request.getParameter("gender");
            Timestamp startTime = parseDate(request.getParameter("startTime"));
            Timestamp endTime = parseDate(request.getParameter("endTime"));
            String residenceType = request.getParameter("residenceType");

            if (occupantName == null || occupantName.trim().isEmpty()) {
                session.setAttribute("error", "姓名不能为空");
                response.sendRedirect("EditOccupantServlet?id=" + residenceId);
                return;
            }

            ResidenceInfo info = new ResidenceInfo();
            info.setResidenceId(residenceId);
            info.setOccupantName(occupantName);
            info.setRelationship(relationship);
            info.setAge(age);
            info.setGender(gender);
            info.setStartTime(startTime);
            info.setEndTime(endTime);
            info.setResidenceType(residenceType);

            boolean success = memberService.updateOccupant(info);
            if (success) {
                session.setAttribute("success", "修改成功！");
                response.sendRedirect("ViewOccupantsServlet");
            } else {
                session.setAttribute("error", "未找到匹配的记录，请检查ID是否正确");
                response.sendRedirect("EditOccupantServlet?id=" + residenceId);
            }

        } catch (NumberFormatException e) {
            session.setAttribute("error", "年龄或ID格式不正确");
            response.sendRedirect("EditOccupantServlet?id=" + request.getParameter("residenceId"));
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("error", "发生未知错误：" + e.getMessage());
            response.sendRedirect("EditOccupantServlet?id=" + request.getParameter("residenceId"));
        }
    }

    private Timestamp parseDate(String dateStr) {
        if (dateStr == null || dateStr.isEmpty()) return null;
        try {
            return new Timestamp(dateFormat.parse(dateStr).getTime());
        } catch (ParseException e) {
            return null;
        }
    }


}